#!/bin/bash
set -eu
if [ $EUID -ne 0 ]; then
    echo "You must be root!" >&2
    exit 1
fi

readonly interval_num=${1:-60}
readonly interval_sleep=${2:-10}

readonly container_id="${3:-$(sudo docker inspect weavescope | jq -r .[].Id)}"
readonly cpuacct_stat="/sys/fs/cgroup/cpu,cpuacct/docker/${container_id}/cpuacct.stat"

TIME_U1=0
TIME_K1=0
TIME_T1=0
TIME_U2=0
TIME_K2=0
TIME_T2=0

if [ "$(pidof scope-probe)" == "" ]; then
    echo "No scope-probe process running - aborting" >&2
    exit 1
fi

TIME_U2=$(awk '/user/ {print $2}' "${cpuacct_stat}")
TIME_K2=$(awk '/system/ {print $2}' "${cpuacct_stat}")
TIME_T2=$((TIME_U2 + TIME_K2))

echo "utime;stime;total_time"
for ((i = 0; i < interval_num; i++)); do
    sleep "$interval_sleep"
    TIME_U1=$TIME_U2
    TIME_K1=$TIME_K2
    TIME_T1=$TIME_T2

    TIME_U2=$(awk '/user/ {print $2}' "${cpuacct_stat}")
    TIME_K2=$(awk '/system/ {print $2}' "${cpuacct_stat}")
    TIME_T2=$((TIME_U2 + TIME_K2))
    echo "$((TIME_U2 - TIME_U1));$((TIME_K2 - TIME_K1));$((TIME_T2 - TIME_T1))"
done
